package com.missfresh.cooperation2meituan.runner;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.missfresh.cooperation2meituan.dao.OrderDao;
import com.missfresh.cooperation2meituan.util.AddressUtil;
import com.missfresh.cooperation2meituan.util.CommonUtil;
import com.missfresh.cooperation2meituan.util.HttpRaw;
import com.missfresh.cooperation2meituan.util.HttpUtil;
import com.missfresh.cooperation2meituan.util.JsonUtil;
import com.missfresh.cooperation2meituan.util.SignUtil;
import com.missfresh.cooperation2meituan.vo.SysOrder;
import com.missfresh.cooperation2meituan.vo.SysOrderDetail;

@Component
public class HandleOrderRunner implements Runnable {
	
	private static final Logger logger = LoggerFactory.getLogger(HandleOrderRunner.class);
	
	@Resource
	private OrderDao orderDao;
	
	@Value("${app.id}")
	private String app_id;
	
	@Value("${retry.num}")
	private int retryNum;
	
	private int sleepTime = 6000;
	
	@Value("${ATP_CREATEORDER_URL}")
	private String ATP_CREATEORDER_URL;
	
	@Value("${MA_CREATEORDER_URL}")
	private String MA_CREATEORDER_URL;
	
	@Value("${CONFIRM_URL}")
	private String CONFIRM_URL;
	
	@Value("${CANCEL_URL}")
	private String CANCEL_URL;
	
	private Map<String, Object> param;
	
	public Map<String, Object> getParam() {
		return param;
	}

	public void setParam(Map<String, Object> param) {
		this.param = param;
	}

	public HandleOrderRunner(){
	} 
	
	public HandleOrderRunner(Map<String, Object> param){
		this.param = param;
	} 

	@Override
	public void run() {
		try {
			logger.info("美团外卖订单处理启动线程");
			boolean isMaSuccess = false;
			//boolean isMaSuccess = true;
			Map<String, Object> ordermap = (Map<String, Object>) param.get("ordermap");
			String order_id = ordermap.get("t_id").toString();
			logger.info("向ATP推送的数据"+JsonUtil.obj2json(ordermap));
			String asresult = HttpRaw.postRaw(ATP_CREATEORDER_URL, JsonUtil.obj2json(ordermap));
			logger.info("库存检查返回结果:"+asresult);
			Map<String, Object> asmap = JsonUtil.json2map(asresult);
			String reason = "";
			String reason_code = "";
			if("CREATED".equals(asmap.get("httpStatus"))){
				if(orderDao.updateInventorySuccess(order_id)>0){
					logger.info("库存检查成功,订单号["+order_id+"]");
					SysOrder sysorder = new SysOrder();
					Map<String, Object> maordermap = (Map<String, Object>) param.get("maordermap");
					sysorder.setTid(maordermap.get("t_id").toString());
					logger.info("库存检查成功,美团订单号["+maordermap.get("t_id").toString()+"]");
					//sysorder.setCreated(maordermap.get("created").toString());
					sysorder.setCreated(CommonUtil.dateToString(new Date()));
					sysorder.setTotal_fee(new BigDecimal((String)maordermap.get("total_fee")));
					sysorder.setLat(maordermap.get("lat").toString());
					/*sysorder.setPay_time(maordermap.get("pay_time").toString());
					sysorder.setDelivery_time(maordermap.get("delivery_time").toString());*/
					sysorder.setPay_time(CommonUtil.dateToString(new Date()));
					sysorder.setDelivery_time(CommonUtil.after2HourDate(new Date()));
					sysorder.setReceiver_mobile(maordermap.get("receiver_mobile").toString());
					String address = maordermap.get("receiver_address").toString();
					sysorder.setReceiver_address(address);
					String provinces = AddressUtil.getCountryMap(address).get("provinces");
					String city = AddressUtil.getCountryMap(address).get("city");
					if(provinces==null || provinces.equals("")){
						provinces = AddressUtil.createProvinces(city);
					} 
					sysorder.setReceiver_state(provinces);
					sysorder.setReceiver_city(city);
					sysorder.setReceiver_district(AddressUtil.getCountryMap(address).get("area"));
					sysorder.setReceiver_name(maordermap.get("receiver_name").toString());
					sysorder.setLng(maordermap.get("lng").toString());
					sysorder.setPost_fee( new BigDecimal((String) maordermap.get("post_fee")));
					//sysorder.setPay_type(maordermap.get("pay_type").toString());
					sysorder.setRange(120);
					sysorder.setStation_code(maordermap.get("station_code").toString());
					BigDecimal num = (BigDecimal) maordermap.get("num");
					sysorder.setNum(num.intValue());
					sysorder.setDiscount_fee((BigDecimal) maordermap.get("discount_fee"));
					sysorder.setPayment((BigDecimal) maordermap.get("payment"));
					sysorder.setOrders((List<SysOrderDetail>) maordermap.get("orders"));
					logger.info("向MA推送的数据"+JsonUtil.obj2json(sysorder));
					String maresult = HttpRaw.postRaw(MA_CREATEORDER_URL, JsonUtil.obj2json(sysorder));
					logger.info("创建订单返回结果:"+maresult);
					Map<String, Object> mamap = JsonUtil.json2map(maresult);
					if("订单创建成功".equals(mamap.get("message"))){
						isMaSuccess = true;
						orderDao.updateOrdersysSuccess(order_id);
						logger.info("订单创建成功,订单号["+order_id+"]");
						logger.info("订单创建成功,美团订单号["+maordermap.get("t_id").toString()+"]");
					}else{
						reason = (String) mamap.get("message");
						reason_code = "1301";
						orderDao.updateOrdersysFail(order_id);
						logger.info("创建订单失败:"+asmap.get("msg")+"订单号["+order_id+"]");
						logger.info("美团订单号["+maordermap.get("t_id").toString()+"]");
					}
					
				}
			}else if("BAD_REQUEST".equals(asmap.get("httpStatus"))){
				reason = "占用库存失败,sku:"+asmap.get("msg");
				reason_code = "1301";
				orderDao.updateInventoryFail(order_id);
				logger.info("占用库存失败,sku:"+asmap.get("msg"));
			}else if("CONFLICT".equals(asmap.get("httpStatus"))){
				reason = "订单号["+order_id+"]重复";
				reason_code = "1203";
				orderDao.updateInventoryFail(order_id);
				logger.info("订单号["+order_id+"]重复");
			}else{
				if("INTERNAL_SERVER_ERROR".equals(asmap.get("httpStatus"))){
					reason = "系统异常:"+asmap.get("msg");
					reason_code = "1301";
					orderDao.updateInventoryFail(order_id);
					logger.info("系统异常:"+asmap.get("msg"));
				}else{
					reason = "系统内部错误";
					reason_code = "1301";
					orderDao.updateInventoryFail(order_id);
					logger.info("系统内部错误");
				}
			}
			if(isMaSuccess){
				logger.info("创建订单成功，开始向美团外卖确实订单");
				List<String> list = new ArrayList<String>();
				list.add("app_id="+app_id);
				String timestamp = System.currentTimeMillis()+"";
				list.add("timestamp="+timestamp);
				list.add("order_id="+order_id);
				String sig = SignUtil.createSign(list, CONFIRM_URL);
				String mtwm_param = "app_id="+app_id+"&timestamp="+timestamp+"&order_id="+order_id+"&sig="+sig;
				String mtwm_result = HttpUtil.sendGet(CONFIRM_URL, mtwm_param);
				logger.info("美团外卖确认订单，美团返回数据："+mtwm_result);
				
				Map<String, Object> resultmap = JsonUtil.json2map(mtwm_result);
				if("ok".equals(resultmap.get("data"))){
					orderDao.updateMeituanSuccess(order_id);
					logger.info("美团外卖确认订单成功:["+order_id+"]");
				}else{
					boolean retrySuccess = false;
					for(int i=0;i<retryNum;i++){
						mtwm_result = HttpUtil.sendGet(CONFIRM_URL, mtwm_param);
						TimeUnit.MILLISECONDS.sleep(sleepTime);
						if("ok".equals(resultmap.get("data"))){
							retrySuccess = true;
							break;
						}
					}
					if(retrySuccess){
						orderDao.updateMeituanSuccess(order_id);
						logger.info("美团外卖确认订单成功:["+order_id+"]");
						
					}else{
						logger.info("美团外卖确认订单失败:["+order_id+"]");
					}
				}
			}else{
				logger.info("创建订单失败，开始向美团外卖取消订单");
				List<String> list = new ArrayList<String>();
				list.add("app_id="+app_id);
				String timestamp = System.currentTimeMillis()+"";
				list.add("timestamp="+timestamp);
				list.add("order_id="+order_id);
				reason = "orderRepeat";
				list.add("reason="+reason);
				list.add("reason_code="+reason_code);
				String sig = SignUtil.createSign(list, CANCEL_URL);
				String mtwm_param = "app_id="+app_id+"&timestamp="+timestamp+"&order_id="+order_id+
						"&reason="+reason+"&reason_code="+reason_code+"&sig="+sig;
				String mtwm_result = HttpUtil.sendGet(CANCEL_URL, mtwm_param);
				logger.info("美团外卖取消订单，美团返回数据："+mtwm_result);
				Map<String, Object> resultmap = JsonUtil.json2map(mtwm_result);
				if("ok".equals(resultmap.get("data"))){
					logger.info("向美团外卖取消订单成功:["+order_id+"]");
				}else{
					boolean retrySuccess = false;
					for(int i=0;i<retryNum;i++){
						mtwm_result = HttpUtil.sendGet(CANCEL_URL, mtwm_param);
						TimeUnit.MILLISECONDS.sleep(sleepTime);
						if("ok".equals(resultmap.get("data"))){
							retrySuccess = true;
							break;
						}
					}
					if(retrySuccess){
						logger.info("向美团外卖取消订单成功:["+order_id+"]");
					}else{
						logger.info("向美团外卖取消订单失败:["+order_id+"]");
					}
				}
			}
			
		} catch (Exception e) {
			logger.error("下发订单线程异常", e);
			e.printStackTrace();
		}
		

	}
	
}
